package com.compty.paint.web.front;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.compty.core.framework.context.spring.SpringContextHolder;
import com.compty.core.framework.context.webcontext.ThreadContextHolder;
import com.compty.core.framework.util.DateUtil;
import com.compty.core.framework.util.HttpUtil;
import com.compty.core.framework.util.MailUtil;
import com.compty.core.framework.util.StringUtil;
import com.compty.core.struts2.BaseAction;
import com.compty.core.utils.CommonsUtil;
import com.compty.paint.domain.AddressInfo;
import com.compty.paint.domain.Bid;
import com.compty.paint.domain.BidRecord;
import com.compty.paint.domain.CustomerInfo;
import com.compty.paint.domain.Goods;
import com.compty.paint.domain.LogInfo;
import com.compty.paint.domain.ProvinceInfo;
import com.compty.paint.domain.SmsReport;
import com.compty.paint.domain.support.CustomerLogTypeEnum;
import com.compty.paint.manager.AddressInfoManager;
import com.compty.paint.manager.AdvanceLogsManager;
import com.compty.paint.manager.BidManager;
import com.compty.paint.manager.BidRecordManager;
import com.compty.paint.manager.CustomerInfoManager;
import com.compty.paint.manager.GoodsManager;
import com.compty.paint.manager.LogInfoManager;
import com.compty.paint.manager.OrderManager;
import com.compty.paint.manager.PaintingManager;
import com.compty.paint.manager.ProvinceInfoManager;
import com.compty.paint.manager.SmsReportManager;
import com.compty.paint.manager.UserInfoManager;
import com.compty.paint.manager.UserStateManager;
import com.compty.paint.service.ISmsService;
import com.compty.paint.service.IUserService;
import com.compty.paint.util.Constants;
import com.compty.security.domain.User;
import com.compty.security.domain.UserState;
import com.compty.security.manager.UserManager;

/**
 * @Todo:前台用户(可参加拍卖)操作处理Action
 * @author: 朱庆辉
 * @CreateTime:2012-4-12 上午11:52:40
 */
public class CustomerAction  extends BaseAction<CustomerInfo>{
	
	private static final long serialVersionUID = -271884547328736935L;
	
	private static Log logger = LogFactory.getLog(CustomerAction.class);
	
	private LogInfoManager logInfoManager;
	private transient CustomerInfoManager customerInfoManager;
	private transient UserManager userManager;
	private transient ProvinceInfoManager provinceInfoManager;
	private transient UserStateManager userStateManager;
	private transient BidRecordManager bidRecordManager;
	private transient AdvanceLogsManager advanceLogsManager;
	private transient AddressInfoManager  addressInfoManager;
	
	private CustomerInfo customerInfo;
	private Date startDate;
	private Date endDate;
	private String title;
	private String backUrl;
	private AddressInfo addressInfo;
	
	/**
	 * 
	 *@Todo:注册prepare
	 *@param uid 推荐人ID
	 *@CreateTime:2012-2-8 下午03:49:57
	 */
	public String registerPrepare(){
		
		List<ProvinceInfo> provinceInfoList = provinceInfoManager.getAll();
		request.setAttribute("provinceInfoList", provinceInfoList);
		
		String recommendUserIdStr = request.getParameter("uid");//推荐人ID
		if( recommendUserIdStr != null ){
			try {
				Long uid = Long.parseLong(recommendUserIdStr);
				User recommendUser = userManager.get(uid);
				session.setAttribute("recommendUser", recommendUser);
			} catch (NumberFormatException e) {
				logger.error(e.getMessage());
			}
		}
		
		String register_from = request.getParameter("register_from");//注册页面来源
		if( "order".equals(register_from)){
			
			String gId = request.getParameter("gId");
			String num = request.getParameter("num");
			
			session.setAttribute("register_from", "order");
			session.setAttribute("register_gId", gId);
			session.setAttribute("register_num", num);
		}
		
		return "registerPrepare";
	}
	
	/**
	 * 获取短信验证码
	 */
	public String fetchSmsCode(){
		
		try {
			String sMobile = request.getParameter("sms_mobile");
			if(!StringUtil.validMobile(sMobile)){
				request.setAttribute("ajaxData","{code:\"0001\",message:\"请填写合法的手机号码。\"}");
				return "sms_code";
			}
			
			String clientIp = request.getRemoteAddr();
			SmsReportManager smsReportManager = SpringContextHolder.getBean("smsReportManager");
			String flag  = smsReportManager.checkByMobileAndIp(sMobile,clientIp);
			String returnMsg = "";
			if( flag == null){
				returnMsg = "缺少参数或参数错误";
			}
			else if("1".equals(flag)){
				returnMsg = "号码验证成功。";
			}
			else if("2".equals(flag)){
				returnMsg = "该号码已注册。";
			}
			else if("3".equals(flag)){
				returnMsg = "同一IP今日只允许获取短信激活码三次，您已超过最大使用次数。";
			}
			else if("4".equals(flag)){
				returnMsg = "该号码今日最多能获取三次激活码，您已超过最大使用次数。";
			}
			if( !"1".equals(flag) ){
				request.setAttribute("ajaxData","{code:\""+flag+"\",message:\""+returnMsg+"\"}");
				return "sms_code";
			}
			
			String sms_code = StringUtil.getRandStr(6);//短信验证码
			ISmsService smsService = SpringContextHolder.getBean("smsService");
			String smsNo  = smsService.sendMessage(sMobile, sms_code);//sms信息编号
			if( smsNo != null ){
				SmsReport smsReport = buildSmsReport(sMobile,smsNo);
				smsReportManager.save(smsReport);
				
				 session.setAttribute("smsCode",sms_code);
				 request.setAttribute("ajaxData","{code:\"0000\",message:\"短信验证码已成功发送，请注意查收。\"}");
			}else{
				request.setAttribute("ajaxData","{code:\"0001\",message:\"短信验证码发送失败，请重新获取。\"}");
			}
			 
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("ajaxData","{code:\"0001\",message:\"短信验证码发送失败，请重新获取。\"}");
		}
		
		return "sms_code";
	}
	
	/**
	 *@Todo:注册成功后跳转
	 *@CreateTime:2012-2-8 下午03:50:11
	 */
	public String register(){
		
		try {
			if( customerInfo != null ){
				String orginalPwd = customerInfo.getPasswd();
				customerInfo.setPasswd(CommonsUtil.getMD5(orginalPwd)); //将密码用md5加密
				customerInfo.setRegisterTime(Calendar.getInstance().getTime());
				customerInfo.setMobile(customerInfo.getUserName());
				
				String sms_code = request.getParameter("sms_code");
				Object sms_code_in_session  = session.getAttribute("smsCode");
				if( sms_code_in_session == null || !sms_code.equals((String)sms_code_in_session)){
					request.setAttribute("errormessge", "请输入正确的短信激活码。");
					return "error";
				}
				
				UserState userState = userStateManager.findUniqueBy("english_name",Constants.User_State_Normal); //设置用户初始状态审核通过，正常
				customerInfo.setUserState(userState);
				
				if(session.getAttribute("recommendUser") != null){//推荐人
					User recommendUser = (User) session.getAttribute("recommendUser");
					customerInfo.setRecommendUser(recommendUser);
				}
				
				customerInfoManager.save(customerInfo);
				session.setAttribute(Constants.CustomerInfo, customerInfo);
				
				sendMailMessage(customerInfo,orginalPwd);//发送邮件通知
				
				Object register_from = session.getAttribute("register_from");
				if(register_from != null && "order".equals((String)register_from)){
					
					String context = HttpUtil.getFullContext(request);
					String gId = (String)session.getAttribute("register_gId");
					String num = (String)session.getAttribute("register_num");
					
					this.setBackUrl(context+"/customer/order!orderPrepare.do?gId="+gId+"&num="+num);
					return "jumpToOrderConfirm";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "register";
	}
	
	/****** 发送邮件 **********/
	private void sendMailMessage(CustomerInfo cust,String orginalPwd) {
		String emailAddress = cust.getEmail();
		if(StringUtil.validEmail(emailAddress)){
			String title = "欢迎成为可观艺术网会员";
			String content = "尊敬的用户您已成功注册为可观艺术网会员，您的登录账号是"+cust.getUserName()+"，密码是"+orginalPwd+"。请妥善保管";
			MailUtil.sendTextMail(emailAddress, title, content);
		}
	}
	
	/**
	 *@Todo:用户修改资料prepare
	 *@CreateTime:2012-2-8 下午02:26:18
	 * @return
	 */
	public String modifyPrepare(){
		
		CustomerInfo customer = (CustomerInfo) session.getAttribute(Constants.CustomerInfo);
		
		if (customer != null) {
			
			Long id = customer.getId();
			this.customerInfo  = customerInfoManager.get(id);
			
			List<ProvinceInfo> provinceInfoList = provinceInfoManager.getAll();
			request.setAttribute("provinceInfoList", provinceInfoList);
			
		}
		
		return "modifyPrepare";
	}
	
	/**
	 *@Todo:修改用户基本资料
	 *@CreateTime:2012-2-8 上午11:14:58
	 * @return
	 */
	public String modifyInformation(){
		
		if( this.customerInfo != null){
			
    		CustomerInfo  customer = customerInfoManager.get(customerInfo.getId());
    		
    		customer.setAddress(customerInfo.getAddress());
    		customer.setCityInfo(customerInfo.getCityInfo());
    		customer.setCustomerName(customerInfo.getUserName());
    		customer.setEmail(customerInfo.getEmail());
    		customer.setIdCard(customerInfo.getIdCard());
    		customer.setMobile(customerInfo.getMobile());
    		customer.setProvinceInfo(customerInfo.getProvinceInfo());
    		customer.setRegionInfo(customerInfo.getRegionInfo());
    		customer.setSex(customerInfo.getSex());
    		customer.setCustomerName(customerInfo.getCustomerName());
    		customer.setTelphone(customerInfo.getTelphone());
    		customer.setZipCode(customerInfo.getZipCode());
    		
    		customerInfoManager.save(customer);
    		
    		session.setAttribute(Constants.CustomerInfo, customerInfo);
    		
			LogInfo logInfo = buildCustomerLogInfo(CustomerLogTypeEnum.customer_modifyInformation, "修改个人资料成功");
			logInfoManager.writeLog(logInfo);
		}
		
		return "modifyInformation";
	}
	
	/**
	 *@Todo:修改密码
	 *@CreateTime:2012-2-8 上午09:56:31
	 * @return
	 */
	public String changePwd(){
		
		if( customerInfo != null){
    		CustomerInfo   customer = customerInfoManager.get(customerInfo.getId());
    		String original_pwd = request.getParameter("original_pwd");
    		String pwd = request.getParameter("pwd");
    		
    		if(!CommonsUtil.getMD5(original_pwd).equals(customer.getPasswd())){
    			this.addActionMessage("您输入的原密码不正确，请重新输入。");
    			return "change_pwd";
    		}else{
    			customer.setPasswd(CommonsUtil.getMD5(pwd));
    			customerInfoManager.save(customer);
        		
        		this.addActionMessage("修改密码成功。");
        		
    			LogInfo logInfo = buildCustomerLogInfo(CustomerLogTypeEnum.customer_modifyInformation, "修改密码成功");
    			logInfoManager.writeLog(logInfo);
    		}
		}
		
		return "change_pwd";
	}
	
	/***会员登录**/
	@SuppressWarnings("unchecked")
	public String login(){
		
		String username = request.getParameter("j_username");
		String password = request.getParameter("j_password");
		String captcha_parameter = request.getParameter("_captcha_parameter");
		Object check_code  = session.getAttribute("check_code");
		
		if(check_code == null || ! captcha_parameter.equals((String)check_code)){
			request.setAttribute("errormessge", "验证码错误");
			return "login";
		}
		
		List list = customerInfoManager.login(username, password);
		Integer returnFlag = (Integer) list.get(0);
		if( returnFlag == -1 ){
			request.setAttribute("errormessge", "该用户不存在");
			return "login";
		}
		else if(returnFlag == 2){
			request.setAttribute("errormessge", "密码不正确");
			return "login";
		}
		else if(returnFlag == 3){
			request.setAttribute("errormessge", "用户状态不正常");
			return "login";
		}
		
		if( returnFlag == 1){//登录成功
			CustomerInfo customer = (CustomerInfo) list.get(1);
			LogInfo logInfo = buildCustomerLogInfo(CustomerLogTypeEnum.customer_login, "登录成功");
			logInfo.setUserName(customer.getUserName());
			logInfo.setUserCode(String.valueOf(customer.getId()));
			logInfoManager.writeLog(logInfo);
			session.setAttribute(Constants.CustomerInfo, customer);
			
			ThreadContextHolder.getSessionContext().setAttribute(IUserService.CURRENT_MEMBER_KEY, customer);
		}
		
		return "login_success";
	}
	
	/** 购买时的登录 ***/
	@SuppressWarnings("unchecked")
	public String login_buy(){
		
		String username = request.getParameter("j_username");
		String password = request.getParameter("j_password");
		String captcha_parameter = request.getParameter("_captcha_parameter");
		Object check_code  = session.getAttribute("check_code");
		
		if(check_code == null || ! captcha_parameter.equals((String)check_code)){
			request.setAttribute("errormessge", "验证码错误");
			return "login_buy";
		}
		
		List list = customerInfoManager.login(username, password);
		Integer returnFlag = (Integer) list.get(0);
		if( returnFlag == -1 ){
			request.setAttribute("errormessge", "该用户不存在");
			return "login_buy";
		}
		else if(returnFlag == 2){
			request.setAttribute("errormessge", "密码不正确");
			return "login_buy";
		}
		else if(returnFlag == 3){
			request.setAttribute("errormessge", "用户状态不正常");
			return "login_buy";
		}
		
		if( returnFlag == 1){
			
			logLoginInfo(list);//记录会员用户登录信息
			
			String context = HttpUtil.getFullContext(request);
			String gId = request.getParameter("login_gId");
			String num = request.getParameter("login_num");
			
			String returnUrl = context+"/customer/order!orderPrepare.do?gId="+gId+"&num="+num;
			request.setAttribute("returnUrl", returnUrl);
			request.setAttribute("logonFlag", "1");
			
			return "login_buy";
		}else{
			request.setAttribute("errormessge", "登录失败。");
			return "login_buy";
		}
	}
	
	//记录会员用户登录信息
	@SuppressWarnings("unchecked")
	private void logLoginInfo(List list){
		CustomerInfo customer = (CustomerInfo) list.get(1);
		LogInfo logInfo = buildCustomerLogInfo(CustomerLogTypeEnum.customer_login, "登录成功");
		logInfo.setUserName(customer.getUserName());
		logInfo.setUserCode(String.valueOf(customer.getId()));
		logInfoManager.writeLog(logInfo);
		queryOrderStatusOfCustomer(customer);
		session.setAttribute(Constants.CustomerInfo, customer);
		ThreadContextHolder.getSessionContext().setAttribute(IUserService.CURRENT_MEMBER_KEY, customer);
	}
	
	/*** 拍卖时的登录  ****/
	@SuppressWarnings("unchecked")
	public String login_bid(){
		
		String username = request.getParameter("j_username");
		String password = request.getParameter("j_password");
		String captcha_parameter = request.getParameter("_captcha_parameter");
		Object check_code  = session.getAttribute("check_code");
		
		if(check_code == null || ! captcha_parameter.equals((String)check_code)){
			request.setAttribute("errormessge", "验证码错误");
			return "login_bid";
		}
		
		List list = customerInfoManager.login(username, password);
		Integer returnFlag = (Integer) list.get(0);
		if( returnFlag == -1 ){
			request.setAttribute("errormessge", "该用户不存在");
			return "login_bid";
		}
		else if(returnFlag == 2){
			request.setAttribute("errormessge", "密码不正确");
			return "login_bid";
		}
		else if(returnFlag == 3){
			request.setAttribute("errormessge", "用户状态不正常");
			return "login_bid";
		}
		
		if( returnFlag == 1){
			
			logLoginInfo(list);//记录会员用户登录信息
			
			String context = HttpUtil.getFullContext(request);
			String bid_id = request.getParameter("bid_id");
			String new_price = request.getParameter("new_price");
			String page_title = request.getParameter("page_title");
			String remain_time = request.getParameter("remain_time");
			
			this.setBackUrl(context+"/customer/bid!bid_confirm.do?bid_id="+bid_id+"&new_price="+new_price+"&page_title="+page_title+"&remain_time="+remain_time);
			return "login_bid_success";
		}else{
			request.setAttribute("errormessge", "登录失败。");
			return "login_bid";
		}
	}
	
	/******** 重置用户密码(会员、商户)  ***********/
	public String forgetpwd(){
		String userType = request.getParameter("userType");//1：表示会员2：表示商户
		String u_name = request.getParameter("u_name");
		if("1".equals(userType)){
			if( u_name == null || "".equals(u_name)){
				request.setAttribute("errormessge", "请先填写登录用户名。");
				return "input_customer";
			}
			CustomerInfo customerInfo = customerInfoManager.findByName(u_name);
			if( customerInfo == null){
				request.setAttribute("errormessge", "该用户名未在本网站注册。");
				return "input_customer";
			}
			String emailAddress = customerInfo.getEmail();
			if( emailAddress == null){
				request.setAttribute("errormessge", "您注册时未填写找回密码邮箱，为保证您的信息安全不被盗用，请使用新手机号码重新注册。");
				return "input_customer";
			}
			if(StringUtil.validEmail(emailAddress)){
				String newPwd = StringUtil.getRandStr(8);
				customerInfo.setPasswd(CommonsUtil.getMD5(newPwd));
				customerInfoManager.save(customerInfo);
				String title = "您的密码已重置";
				String content = "尊敬的用户您的密码已重置，您的登录账号是"+u_name+"，新密码是"+newPwd+"。请登录后修改密码。";
				MailUtil.sendTextMail(emailAddress, title, content);
				request.setAttribute("returnMsg", "新密码已经发至您的邮箱"+emailAddress);
			}else{
				request.setAttribute("errormessge", "您注册时未填写找回密码邮箱，为保证您的信息安全不被盗用，请使用新手机号码重新注册。");
				return "input_customer";
			}
		}else{
			if( u_name == null || "".equals(u_name)){
				request.setAttribute("errormessge", "请先填写登录用户名。");
				return "input_member";
			}
			UserInfoManager userInfoManager =  SpringContextHolder.getBean("userInfoManager");
			User user = userInfoManager.findByName(u_name);
			if( user == null){
				request.setAttribute("errormessge", "该用户名未在本网站注册。");
				return "input_member";
			}
			String emailAddress = user.getEmailAddress();
			if(emailAddress == null){
				request.setAttribute("errormessge", "您注册时未填写找回密码邮箱，请用新用户名重新注册或联系客服。");
				return "input_member";
			}
			if(StringUtil.validEmail(emailAddress)){
				String newPwd = StringUtil.getRandStr(8);
				user.setPassword(CommonsUtil.getMD5(newPwd));
				userManager.save(user);
				String title = "您的密码已重置";
				String content = "尊敬的用户您的密码已重置，您的登录账号是"+u_name+"，新密码是"+newPwd+"。请登录后修改密码。";
				MailUtil.sendTextMail(emailAddress, title, content);
				request.setAttribute("returnMsg", "新密码已经发至您的邮箱"+emailAddress);
			}
			else{
				request.setAttribute("errormessge", "您注册时未填写找回密码邮箱，为保证您的信息安全不被盗用，请使用新手机号码重新注册。");
				return "input_member";
			}
		}
		return "forgetpwd";
	}
	
	/***查询用户订单概况**/
	private void queryOrderStatusOfCustomer(CustomerInfo customer){
		OrderManager orderManager = SpringContextHolder.getBean("orderManager");
		
		int totalOrder = orderManager.queryTotalOrderCount(customer);
		int payedOrder = orderManager.queryPayedOrderCount(customer);
		int notPayOrder = orderManager.queryNotPayOrderCount(customer);
		
		session.setAttribute("count_total_order", totalOrder);
		session.setAttribute("count_payed_order", payedOrder);
		session.setAttribute("count_notpay_order", notPayOrder);
	}
	
	public void checkLogon(){
		
		Object customerInfo =  session.getAttribute(Constants.CustomerInfo);
		
		if( customerInfo != null){
			String userName = ((CustomerInfo)customerInfo).getUserName();
			String returnMsg =  userName+",&nbsp;&nbsp;欢迎进入<a href=\"/customer/customerAction!index.do\" style=\"color: #979797\">会员账户中心</a>&nbsp;&nbsp;<a href=\"/customer/customerAction!modifyPrepare.do\" style=\"color: #979797\">修改资料</a>&nbsp;&nbsp;<a href=\"/customer/customerAction!changePwd.do\" style=\"color: #979797\">修改密码</a>|&nbsp;&nbsp;<a href=\"/customer/customerAction!logout.do\" style=\"color: #979797\">退出</a>";
			out.print(returnMsg);
		}else{
			String returnMsg =  "<a href=\"javascript:toLogon()\" style=\"color: #979797\">会员登录</a>|&nbsp;&nbsp;<a href=\"/customer/customerAction!registerPrepare.do\" style=\"color: #979797\">注册</a>";
			out.print(returnMsg);
		}
	}
	
	/**
	 *@Todo:登出
	 *@CreateTime:2012-2-8 下午04:32:17
	 * @return
	 */
	public String logout(){
		
		CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Constants.CustomerInfo);
    	if( customerInfo != null){
			LogInfo logInfo = buildCustomerLogInfo(CustomerLogTypeEnum.customer_logout, "登出成功");
			logInfoManager.writeLog(logInfo);
    	}
		
		session.removeAttribute(Constants.CustomerInfo);
		session.invalidate();
		
		return "logout";
		
	}
	
	/**
	 *会员中心首页(查询订单记录)
	 */
	@SuppressWarnings("unchecked")
	public String index(){
		
		CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Constants.CustomerInfo);
		
		if( customerInfo != null ){
			 OrderManager orderManager = SpringContextHolder.getBean("orderManager");
			page = orderManager.listAllOrder(curPage,pageSize,customerInfo);
		}
		
		PaintingManager paintingManager = SpringContextHolder.getBean("paintingManager");
		List list  = paintingManager.findNewestSale(4);
		session.setAttribute("newest_list", list);
		
		queryOrderStatusOfCustomer(customerInfo);
		
		return "index";
	}
	
	/**
	 *@Todo:查询拍卖记录
	 *@CreateTime:2012-2-14 上午11:47:44
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String queryBidRecord(){
		
		CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Constants.CustomerInfo);
		
		if( customerInfo != null ){
			this.page = bidRecordManager.queryUniqueBidRecord(curPage, pageSize,customerInfo);
			List list = (List) page.getResult();
			for (int i = 0; i < list.size(); i++) {
				BidRecord bidRecord = (BidRecord) list.get(i);
				Bid bid = bidRecord.getBid();
				BidManager bidManager = SpringContextHolder.getBean("bidManager");
				bid = bidManager.findById(bid.getId());
				Integer goods_id = bid.getGoods_id();
				GoodsManager goodsManager = SpringContextHolder.getBean("goodsManager");
				Goods goods = goodsManager.findById(goods_id);
				bid.setGoods(goods);
			}
		}
		
		return "bid_record";
	}
	
	/**
	 *@Todo:账务查询
	 *@CreateTime:2012-2-28 上午10:12:06
	 * @return
	 */
	public String queryAccountInfo(){
		
		CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Constants.CustomerInfo);
		
		if( customerInfo != null ){
			Object[] param = new Object[1];
			String hql = " from AdvanceLogs where member_id = ?";
			param[0] = customerInfo.getId();
			this.page = advanceLogsManager.pagedQuery(hql, curPage, pageSize,param);
		}
		
		return "account_info";
	}
	
	/**
	 *@Todo:预存储账户充值
	 *@CreateTime:2012-2-28 上午11:33:56
	 * @return
	 */
	public String preStore(){
		
		return "prestore";
	}
	
	/**
	 * 列出客户所有收货地址
	 */
	public String listAddress(){
		
		CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Constants.CustomerInfo);
		
		List<AddressInfo>  addressList = addressInfoManager.findByCustomerInfo(customerInfo);
		request.setAttribute("addressList", addressList);
		
		int size = addressList.size();
		request.setAttribute("sizeOfaddressList", size);
		
		return "listAddress";
	}
	
	/**
	 * 新增收货地址prepare
	 */
	public String addNewAddressPrepare(){
		
		List<ProvinceInfo> provinceInfoList = provinceInfoManager.getAll();
		request.setAttribute("provinceInfoList", provinceInfoList);
		
		return "addNewAddressPrepare";
	}
	
	/**
	 * 保存新收货地址
	 */
	public String saveAddressInfo(){
		
		if( addressInfo != null){
			
			CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Constants.CustomerInfo);
			
			int count_addresses = addressInfoManager.findCountByCustomerInfo(customerInfo);
			if( count_addresses >= 5){
				request.setAttribute("errormessge","每个会员最多允许添加五个收货地址。");
				return "addNewAddressPrepare";
			}
			
			addressInfo.setCustomerInfo(customerInfo);
			addressInfoManager.save(addressInfo);
		}
		
		return "saveAddressInfo";
	}
	
	/***
	 * 删除收货地址
	 */
	public String delAddress(){
		
		String id = request.getParameter("id");
		Integer addressId = Integer.valueOf(id);
		
		addressInfoManager.removeById(addressId);
		
		return "delAddress";
	}
	
	/***
	 * 修改收货地址prepare
	 */
	public String modifyAddressPrepare(){
		
		String id = request.getParameter("id");
		Integer addressId = Integer.valueOf(id);
		this.addressInfo = addressInfoManager.get(addressId);
		
		List<ProvinceInfo> provinceInfoList = provinceInfoManager.getAll();
		request.setAttribute("provinceInfoList", provinceInfoList);
		
		return "modify_address_prepare";
	}
	
	/**
	 * 设置默认地址
	 */
	public String setDefaultAddress(){
		
		CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Constants.CustomerInfo);
		
		String id = request.getParameter("id");
		Integer addressId = Integer.valueOf(id);
		String defaultFlag = request.getParameter("flag");
		
		addressInfoManager.setDefaultAddress(customerInfo,addressId,defaultFlag);
		
		return "setDefaultAddress";
	}
	
	private SmsReport buildSmsReport(String sMobile, String smsNo) {
		SmsReport smsReport = new SmsReport();
		smsReport.setMobile(sMobile);
		smsReport.setSmsNo(smsNo);
		long beginTime = DateUtil.getNow().getTime();
		long endTime = beginTime + 10*60*1000;
		smsReport.setCreateTime(beginTime);
		smsReport.setEndTime(endTime);
		return smsReport;
	}

	public void setCustomerInfoManager(CustomerInfoManager customerInfoManager) {
		this.customerInfoManager = customerInfoManager;
	}

	public void setProvinceInfoManager(ProvinceInfoManager provinceInfoManager) {
		this.provinceInfoManager = provinceInfoManager;
	}

	public CustomerInfo getCustomerInfo() {
		return customerInfo;
	}

	public void setCustomerInfo(CustomerInfo customerInfo) {
		this.customerInfo = customerInfo;
	}

	public void setUserStateManager(UserStateManager userStateManager) {
		this.userStateManager = userStateManager;
	}
	
	public void setLogInfoManager(LogInfoManager logInfoManager) {
		this.logInfoManager = logInfoManager;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setBidRecordManager(BidRecordManager bidRecordManager) {
		this.bidRecordManager = bidRecordManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public void setAdvanceLogsManager(AdvanceLogsManager advanceLogsManager) {
		this.advanceLogsManager = advanceLogsManager;
	}

	public String getBackUrl() {
		return backUrl;
	}

	public void setBackUrl(String backUrl) {
		this.backUrl = backUrl;
	}

	public AddressInfo getAddressInfo() {
		return addressInfo;
	}

	public void setAddressInfo(AddressInfo addressInfo) {
		this.addressInfo = addressInfo;
	}

	public void setAddressInfoManager(AddressInfoManager addressInfoManager) {
		this.addressInfoManager = addressInfoManager;
	}
}
